package com.xiaomi.shwx.service.impl;

import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomi.shwx.common.exception.BaseException;
import com.xiaomi.shwx.common.result.ResultCodeEnum;
import com.xiaomi.shwx.common.util.Constant;
import com.xiaomi.shwx.entity.dto.UserLoginDTO;
import com.xiaomi.shwx.entity.dto.UserRegDTO;
import com.xiaomi.shwx.entity.pojo.User;
import com.xiaomi.shwx.entity.vo.UserLoginVO;
import com.xiaomi.shwx.mapper.UserMapper;
import com.xiaomi.shwx.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Lei
 * @since 2024-05-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public UserLoginVO register(UserRegDTO dto) {
        // 验证账号、手机号、邮箱是否存在
        LambdaQueryChainWrapper<User> wrapperAccount = lambdaQuery().eq(User::getAccount, dto.getAccount());
        LambdaQueryChainWrapper<User> wrapperPhone = lambdaQuery().eq(User::getPhone, dto.getPhone());
        LambdaQueryChainWrapper<User> wrapperEmail = lambdaQuery().eq(User::getEmail, dto.getEmail());
        if (Objects.nonNull(wrapperAccount.one())
                || Objects.nonNull(wrapperPhone.one())
                || Objects.nonNull(wrapperEmail.one())) {
            throw new BaseException(Constant.USER_EXIST, ResultCodeEnum.PARAMS_ERROR.getCode());
        }
        // 密码加密
        dto.setPassword(DigestUtils.md5DigestAsHex(dto.getPassword().getBytes()));
        User user = new User();
        BeanUtils.copyProperties(dto, user);
        UserLoginVO response = new UserLoginVO();
        if (save(user)) {
            BeanUtils.copyProperties(response, dto);
            return response;
        }
        return response.fail();
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        // 根据账号查询用户
        LambdaQueryChainWrapper<User> wrapper = lambdaQuery().eq(User::getAccount, dto.getAccount());
        // 校验是否存在该用户
        User checkUser = wrapper.one();
        if (Objects.isNull(checkUser)){
            throw new BaseException(Constant.USER_NOT_EXIST,ResultCodeEnum.FAIL.getCode());
        }
        UserLoginVO response = new UserLoginVO();
        // 校验密码是否正确
        if (!checkUser.getPassword().equals(DigestUtils.md5DigestAsHex(dto.getPassword().getBytes()))) {
            throw new BaseException(Constant.USER_PASSWORD_ERROR, ResultCodeEnum.FAIL.getCode());
        }
        BeanUtils.copyProperties(checkUser, response);
        return response;
    }
}
